package coop.bancocredicoop.proyectos.gd

import org.apache.commons.logging.LogFactory

import coop.bancocredicoop.proyectos.gd.alfresco.AlfrescoServiceConnection
import coop.bancocredicoop.proyectos.gd.alfresco.Utils

class SecurityFilters {
    
    static final log = LogFactory.getLog(this)
    def grailsApplication
	def rbacFactory

    def filters = {
        all(controller:'*', action:'*') {
            before = {
                
                if (session.usuario != null) {
                    //log.info("usuario is already in session: ${session.usuario.getUserName()}")
                    return true
                } 

                def userName = request.getRemoteUser()
				def rbac = rbacFactory.create(session, userName)
				session.rbac = rbac

                def usuario = rbac.getUsuario()
				removeUserFromAlfrescoGroups(rbac)
                addUserToAlfrescoGroups(rbac) 
                session.usuario = usuario
                return true

            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }
    }

    private def addUserToAlfrescoGroups(rbac) {

        def usuario = rbac.getUsuario()
        def actingAsUser = grailsApplication.config.alfresco.credentials.user
        def alfClient = new Utils(grailsApplication.config.alfresco)
                                .getClient(loggedInUser: actingAsUser)

        def addUserToGroup = { userName, groupName -> 
            def result = alfClient.addUserToGroup(userName, groupName)
            if (result.success) {
                return true
            } else {
                log.error "User '${userName}' could not be added to group '${groupName}': ${result.message}"
                if (result.data) {
                    log.error result.data
                }
                return false
            }
        }

		def rolesAlfrescoHabilitados = rbac.rolesAlfrescoHabilitados()
		
		log.info "Roles Alfresco habilitados: ${rolesAlfrescoHabilitados}"
		
		rolesAlfrescoHabilitados.each { role ->
            def groupName = grailsApplication.config.alfresco.roleMap[role]
            def userName = usuario.getUserName()
            addUserToGroup(userName, groupName)
        }

    }

	private def removeUserFromAlfrescoGroups(rbac) {
		def usuario = rbac.getUsuario()
		def actingAsUser = grailsApplication.config.alfresco.credentials.user
		def alfClient = new Utils(grailsApplication.config.alfresco)
								.getClient(loggedInUser: actingAsUser)

		def removeUserFromGroup = { userName, groupName ->
			def result = alfClient.removeUserFromGroup(userName, groupName)
			if (result.success) {
				return true
			} else {
				log.error "User '${userName}' could not be removed from group '${groupName}': ${result.message}"
				if (result.data) {
					log.error result.data
				}
				return false
			}
		}
		
		def rolesAlfrescoDeshabilitados = rbac.rolesAlfrescoDeshabilitados()
		
		log.info "Roles Alfresco no habilitados: ${rolesAlfrescoDeshabilitados}"
		
		rolesAlfrescoDeshabilitados.each { role ->
			def groupName = grailsApplication.config.alfresco.roleMap[role]
			def userName = usuario.getUserName()
			removeUserFromGroup(userName, groupName)
		}

	}

}
